package com.zzz.demo.utils;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.Set;

/**
 * @author ZZZ
 * @version 1.0
 * @date 2018/10/30 030
 */
public class RedisClusterUtil {

    private static JedisCluster jedisCluster = null;
    private static final int DEFAULT_TIMEOUT = 2000;
    private static final int SO_TIMEOUT = 2000;
    private static final int DEFAULT_MAX_REDIRECTIONS = 5;
    private static final String PASSWORD = "admin";

    static {
        // 添加集群的服务节点Set集合
        Set<HostAndPort> hostAndPortsSet = new HashSet<>();
        // 添加节点
        hostAndPortsSet.add(new HostAndPort("121.40.53.159", 7000));
        hostAndPortsSet.add(new HostAndPort("121.40.53.159", 7001));
        hostAndPortsSet.add(new HostAndPort("121.40.53.159", 7002));
        hostAndPortsSet.add(new HostAndPort("121.40.53.159", 7009));
        hostAndPortsSet.add(new HostAndPort("121.40.53.159", 7010));

        // Jedis连接池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲连接数, 默认8个
        jedisPoolConfig.setMaxIdle(100);
        // 最大连接数, 默认8个
        jedisPoolConfig.setMaxTotal(500);
        // 最小空闲连接数, 默认0
        jedisPoolConfig.setMinIdle(0);
        // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(2000); // 设置2秒
        // 对拿到的connection进行validateObject校验
        jedisPoolConfig.setTestOnBorrow(true);
        // 初始化jedisCluster
        jedisCluster = new JedisCluster(hostAndPortsSet, jedisPoolConfig);
        // 带密码连接
//        jedisCluster = new JedisCluster(hostAndPortsSet, DEFAULT_TIMEOUT, SO_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, PASSWORD, jedisPoolConfig);
    }

    /**
     * @desc 获取jedisCluster
     * @author ZZZ
     * @date 2018/10/30 030
     * @version 1.0
     */
    public static JedisCluster getJedisCluster() {
        return jedisCluster;
    }
}
